<template>
  <div>
    <div class="header-div">
      <el-page-header @back="goBack" :content="sectionData.name" title="" class="head-div l">
      </el-page-header>
      <user-menu class="r login-area"></user-menu>
    </div>
    <div class="video-win">
      <div class="show-left-btn">
        <dl>
<!--          <dd>-->
<!--            <i class="el-icon-notebook-1"></i>-->
<!--            <span>章节</span>-->
<!--          </dd>-->
          <dd @click="showRightFun('qa')">
            <i class="el-icon-s-comment"></i>
            <span>问答</span>
          </dd>
          <dd @click="showRightFun('note')">
            <i class="el-icon-edit-outline"></i>
            <span>笔记</span>
          </dd>
          <dd @click="showComm = true">
            <i class="el-icon-chat-dot-square"></i>
            <span>评论</span>
          </dd>
        </dl>
      </div>
      <div class="show-video" id="show-video-div" >
      </div>
      <div class="show-right-option" id="show-right-option" v-loading="rightLoad" v-if="showRight">
        <div class="header">
          <div class="title">{{rightTitle}}</div>
          <div class="close" @click="showRight = false"><i class="el-icon-close"></i></div>
        </div>
        <div class="option">
          <div class="qa">
            <el-upload
              class="upload_div"
              :auto-upload="true"
              action=""
              :http-request="fileUploadCom"
              :show-file-list="false"
              :multiple="false">
              <el-button id="image-upload">
              </el-button>
            </el-upload>
            <el-input v-if="!showPrt" class="inputDiv" v-model="title" placeholder="请用一句话描述你的问题"></el-input>
            <quill-editor v-model="content"
                          :options="editorOption"
                          ref="QuillEditor"
            ></quill-editor>
            <div class="option-bottom">
              <div class="prt-div" v-if="showPrt">
                <el-switch v-model="isPrt"
                  active-text='截图'
                ></el-switch>
              </div>
              <div class="submit-div">
                <el-button size="small"
                           type="success"
                           @click="rightSubmitFun"
                           style="width: 100px">
                  提交
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="course_learn">
      <!--导航菜单-->
      <div class="course-info-menu">
        <div class="w">
          <el-menu
            :default-active="$route.fullPath"
            class="CourseNavMenu"
            router
            mode="horizontal"
            @select="navMenuSelect"
            :collapse="false"
          >
            <el-menu-item v-for="item in menuList" :key="item.menu_id" :index="item.url" :route="item.route"  class="item_div" >
              <span>
                  {{item.name}}
                </span>
            </el-menu-item>
          </el-menu>
        </div>
      </div>
      <!--下方显示-->
      <div >
        <div class="w">
          <div class="content">
            <router-view :courseId="courseId"></router-view>
          </div>
        </div>

      </div>
    </div>
    <el-dialog
      title="我要评论"
      :visible.sync="showComm"
      modal
      close-on-click-modal
      close-on-press-escape
      show-close
      class="comm-div"
      width="40%">
      <el-input type="textarea"
                placholder="吐槽、表扬、鼓励……想说啥就说啥！"
                v-model="commData.content"
                :rows="4"
                maxlength="300"
                show-word-limit
      ></el-input>
      <div style="margin-top: 20px;text-align: right">
        <el-button type="success"  @click="submitComm">发表评论</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import UserMenu from '../../common/UserMenu'
import Player from 'xgplayer'

export default {
  name: 'CourseLearn',
  data () {
    return {
      courseId: this.$route.query.courseId,
      sectionId: this.$route.query.sectionId,
      sectionData: '',
      player: '',
      title: '',
      content: '',
      isPrt: false,
      showRight: false,
      showPrt: false,
      rightType: '',
      rightTitle: '',
      // 评论窗口
      showComm: false,
      rightLoad: false,
      commData: {
        courseId: this.$route.query.courseId,
        sectionId: this.$route.query.sectionId,
        userId: '',
        star: 0,
        remove: 1,
        content: ''
      },
      menuList: [
        {
          menu_id: '1',
          name: '问答评论',
          url: '/video/courseQC?sectionId=' + this.$route.query.sectionId + '&courseId=' + this.$route.query.courseId + '&path=' + this.$route.query.path
        },
        {
          menu_id: '2',
          name: '同学笔记',
          url: '/video/courseNote?sectionId=' + this.$route.query.sectionId + '&courseId=' + this.$route.query.courseId + '&path=' + this.$route.query.path
        },
        {
          menu_id: '3',
          name: '课程资料',
          url: '/video/courseFile?sectionId=' + this.$route.query.sectionId + '&courseId=' + this.$route.query.courseId + '&path=' + this.$route.query.path
        }
      ],
      editorOption: {
        theme: 'snow',
        modules: {
          toolbar: {
            container: [['code-block', 'blockquote'], // 引用，代码块
              ['bold', 'italic'], // 加粗，斜体，下划线，删除线
              [{'list': 'ordered'}, {'list': 'bullet'}], // 列表
              ['image'] // 上传图片、上传视频
            ],
            handlers: {
              'image': function (value) {
                if (value) {
                  // 调用iview图片上传
                  document.getElementById('image-upload').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  components: {
    UserMenu
  },
  mounted () {
    this.getSectionData()
    this.commData.userId = this.user.userId
  },
  computed: mapState({
    user: 'user'
  }),
  methods: {
    navMenuSelect () {},
    goBack () {
      this.$router.push(this.$route.query.path)
    },
    getSectionData () {
      var _this = this
      this.$axios.post('/api/section/getSection',
        _this.$qs.stringify({
          sectionId: _this.sectionId
        })
      )
        .then(function (response) {
          var result = response.data
          if (result.isSuccess) {
            _this.sectionData = JSON.parse(JSON.stringify(result.result))
            _this.videoInit(_this.sectionData.videoUrl)
          }
        })
    },
    videoInit (url) {
      let player = new Player({
        id: 'show-video-div',
        url: url,
        width: '100%',
        height: '100%',
        autoplay: true,
        videoInit: true,
        playbackRate: [1, 2],
        defaultPlaybackRate: 1
      })
      this.player = player
    },
    async fileUploadCom (file) {
      var _this = this
      var host = this.$store.state.ossData.host
      var response = this.$Utils.getSignature('prtImage')
      var requestData = new FormData()
      await response.then(res => {
        requestData = this.$Utils.fileUpload(file.file, res)
      })
      await this.$axios.post(host, requestData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: progressEvent => {
          let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
          _this.fileProgress = complete
          // file.onProgress({percent: complete})
        }
      })
        .then(function (response) {
          // eslint-disable-next-line eqeqeq
          if (response.status == 200) {
            _this.insertImage(host + '/' + requestData.get('key'))
          }
        })
    },
    insertImage (res) {
      // 获取富文本组件实例
      let quill = this.$refs.QuillEditor.quill
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let length = quill.getSelection().index
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', res)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        // 提示信息，需引入Message
        this.$message({
          type: 'error',
          message: '图片插入失败!'
        })
      }
    },
    submitFun () {
    },
    showRightFun (type) {
      // eslint-disable-next-line eqeqeq
      if (type == 'qa') {
        this.rightTitle = '提问题'
        this.rightType = 'qa'
        this.showRight = true
        this.showPrt = false
        // eslint-disable-next-line eqeqeq
      } else if (type == 'note') {
        this.rightTitle = '写笔记'
        this.rightType = 'note'
        this.showRight = true
        this.showPrt = true
      }
    },
    rightSubmitFun () {
      this.rightLoad = true
      // eslint-disable-next-line eqeqeq
      if (this.rightType == 'qa') {
        this.submitQuestion()
        // eslint-disable-next-line eqeqeq
      } else if (this.rightType == 'note') {
        this.submitNote()
      }
    },
    // 发表评论
    submitComm () {
      var _this = this
      this.$axios.post('/api/comment/addComment',
        this.$qs.stringify({
          'commentData': JSON.stringify(_this.commData)
        })
      ).then(function (response) {
        var result = response.data
        if (result.isSuccess) {
          _this.$message({
            message: '评论成功',
            type: 'success'
          })
          _this.showComm = false
        }
      })
    },
    // 提交问题
    submitQuestion () {
      var _this = this
      var questionData = {}
      questionData.courseId = this.courseId
      questionData.sectionId = this.sectionId
      questionData.userId = this.user.userId
      questionData.title = this.title
      questionData.content = this.content
      this.$axios.post('/api/question/add',
        this.$qs.stringify({
          'questionData': JSON.stringify(questionData)
        })
      ).then(function (response) {
        var result = response.data
        if (result.isSuccess) {
          _this.$message({
            message: '问题提交成功！',
            type: 'success'
          })
          _this.cleanRight()
        } else {
          _this.$message({
            message: '失败，请重试！',
            type: 'error'
          })
        }
        _this.rightLoad = false
      }).catch(function () {
        _this.$message({
          message: '失败，请重试！',
          type: 'error'
        })
        _this.rightLoad = false
      })
    },
    // 提交笔记
    submitNote () {
      var _this = this
      var noteData = {}
      noteData.userId = this.user.userId
      noteData.courseId = this.courseId
      noteData.sectionId = this.sectionId
      noteData.content = this.content
      noteData.screenShot = this.isPrt ? 1 : 0
      if (this.isPrt) {
        var linTime = parseInt(this.player.currentTime * 1000)
        noteData.videoTime = linTime
        noteData.screenUrl = this.sectionData.videoUrl + '?x-oss-process=video/snapshot,t_' + linTime.toString() + ',f_jpg,w_0,h_0,m_fast'
      }
      noteData.remove = 1
      this.$axios.post('/api/note/add',
        this.$qs.stringify({
          'noteData': JSON.stringify(noteData)
        })
      ).then(function (response) {
        var result = response.data
        if (result.isSuccess) {
          _this.$message({
            message: '笔记添加成功',
            type: 'success'
          })
          _this.cleanRight()
        } else {
          _this.$message({
            message: '添加失败，请重试!',
            type: 'success'
          })
        }
        _this.rightLoad = false
      }).catch(function () {
        _this.$message({
          message: '失败，请重试！',
          type: 'error'
        })
        _this.rightLoad = false
      })
    },
    cleanRight () {
      this.title = ''
      this.content = ''
      this.isPrt = false
    }

  }
}
</script>

<style scoped>
  .header-div{
    height: 50px;
    z-index: 20;
    box-shadow: 0 4px 8px 0 rgba(28,31,33,.1);
  }
.head-div{
  height: 50px;
  line-height: 50px;
  padding-left: 20px;
}
  .l{
    float: left;
  }
  .r{
    float: right;
  }
  .login-area{
    margin-right: 50px;
    height: 50px;
  }
  .video-win{
    position: relative;
    z-index: 1;
    background-color: #1c1f21;
    overflow: hidden;
    width:100%;
    height:800px;
    display: flex;
  }
  .show-left-btn{
    background: #1c1f21;
    width: 60px;
    display: flex;
    /* display: -webkit-flex; */
    align-items: center;
    z-index: 1;
  }
  .show-video{
    width: 100%;
    height: 100%;
    display: inline-block;
    flex: 1;
    background-color: #000;
  }
  dl {
    margin: 0px;
    padding: 0px;
  }
  dd {
    margin: 0px;
    padding: 0px;
  }
  .show-left-btn dl {
    flex: 1;
    width: 100%;
    margin: auto 0px;
  }
  .show-left-btn dd {
    display: flex;
    height: 72px;
    flex-direction: column;
    text-align: center;
    justify-content: center;
    cursor: pointer;
  }
  .show-left-btn i{
    font-size: 24px;
    color: rgba(255,255,255,.6);
    line-height: 24px;
  }
  .show-left-btn span{
    font-size: 12px;
    color: rgba(255,255,255,.4);
    line-height: 18px;
  }
  .show-right-option{
    z-index: 1;
    width: 500px;
    display: inline-block;
    background-color: #f8fafc;
  }
  .show-right-option .upload_div{
    display: none;
  }
  .show-right-option .header{
    height: 30px;
    text-align: left;
    padding: 10px 20px;
  }
  .show-right-option .title{
    display: inline-block;
    height: 30px;
    line-height: 30px;
  }
  .show-right-option .close{
    display: inline-block;
    height: 30px;
    line-height: 30px;
    float: right;
    font-size: 30px;
    cursor: pointer;
  }
  .show-right-option .option{
    height: 600px;
    background-color: #FFF;
    padding: 10px 20px 20px;
  }
  .option .qa .inputDiv{
    width: 100%;
    margin-bottom: 10px;
  }
  .quill-editor{
    height: 350px;
  }
  .option-bottom {
    margin-top: 50px;
    padding: 0px 0px 20px;
    height: 30px;
    text-align: left;
  }
  .option-bottom .prt-div{
    height: 30px;
    line-height: 30px;
    display: inline-block;
  }
  .option-bottom .submit-div{
    display: inline-block;
    float: right;
    height: 30px;
    line-height: 30px;
  }
  .comm-div{
    text-align: left;
  }
  .el-dialog__body {
    padding: 0px 20px 30px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }
  .course_learn{
    min-height: 600px;
  }
  .course_learn .course-info-menu {
    height: 60px;
    line-height: 60px;
    background: #fff;
    box-shadow: 0 4px 8px 0 rgba(28, 31, 33, .1);
  }
  .course-info-menu .CourseNavMenu{
    border-bottom: 0px;
  }
  .course_learn .w {
    width:1200px;
    height: 100%;
    margin:0px auto;
  }
  .course_learn .content{
    display: inline-block;
    float: left;
    width: 800px;
    padding-top: 30px;
  }
</style>
